﻿using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Configuration;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace Http
{
    public class Requester
    {
        public Requester(string referer) : this()
        {
            Referer = referer;
        }

        public Requester()
        {
            // 防止出现 未能为 ssl/tls 安全通道建立信任关系 这种问题
            ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => true;
        }

        public CookieCollection CookieCollection { get; } = new CookieCollection();

        public string CookieString
        {
            get
            {
                var cookie = string.Empty;
                foreach (Cookie item in CookieCollection)
                {
                    cookie += $"{item.Name}={item.Value}; ";
                }
                cookie = cookie.Substring(0, cookie.Length - 2);
                return cookie;
            }

            set
            {
                var mc = Regex.Matches(value.Trim() + ";", "(.*?)=(.*?);");
                foreach (Match m in mc)
                {
                    try
                    {
                        CookieCollection.Add(new Cookie(m.Groups[1].Value, m.Groups[2].Value, "/", "*"));
                    }
                    catch (Exception) { }
                }

            }
        }

        public string Referer { get; private set; }

        public Response GetResponse(RequestItem item)
        {
            #region 设置HttpWebRequest参数

            var request = (HttpWebRequest) WebRequest.Create(item.Url);
            request.Headers = item.Headers; // 必须第一个设置
            request.Accept = item.Accept;
            request.AllowAutoRedirect = item.Allowautoredirect;
            request.ContentType = item.ContentType;
            request.Method = item.Method.ToString();
            request.Referer = item.Referer;
            request.UserAgent = item.UserAgent;
            request.Proxy = item.Proxy;
            request.KeepAlive = item.KeepAlive;
            request.Timeout = item.Timeout;
            request.ServicePoint.Expect100Continue = item.Expect100Continue;

            CookieCollection.Add(item.CookieCollection);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(CookieCollection);


            if (item.Method == Method.POST)
            {
                var buffer = Encoding.Default.GetBytes(item.PostData);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }

            #endregion 设置HttpWebRequest参数

            HttpWebResponse httpWebResponse;

            try
            {
                httpWebResponse = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                httpWebResponse = ex.Response as HttpWebResponse;
            }
            Debug.Assert(httpWebResponse != null, "httpWebResponse != null");
            
            var response = new Response
            {
                Headers = httpWebResponse.Headers,
                CookiesResponse = httpWebResponse.Cookies,
                StatusDescription = httpWebResponse.StatusDescription,
                StatusCode = httpWebResponse.StatusCode,
                Location = httpWebResponse.Headers["Location"]
            };
            CookieCollection.Add(response.CookiesResponse);

            //if (httpWebResponse.StatusCode != HttpStatusCode.OK) return response;
            //System.Net.ServicePointManager.DefaultConnectionLimit = 50;

            #region 获取 ResponseByte & ResponseString

            //GZIP处理
            if (httpWebResponse.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
            {
                var stream = httpWebResponse.GetResponseStream();
                //开始读取流并设置编码方式
                if (stream != null)
                    response.Byte =
                        Stream2MemoryStream(new GZipStream(stream,
                            CompressionMode.Decompress)).ToArray();
            }
            else
            {
                //开始读取流并设置编码方式
                response.Byte = Stream2MemoryStream(httpWebResponse.GetResponseStream()).ToArray();
            }

            //byte -> string
            if (item.Encoding != null)
            {
                response.String = item.Encoding.GetString(response.Byte);
            }
            else if (!string.IsNullOrEmpty(httpWebResponse.CharacterSet))
            {
                response.String = Encoding.GetEncoding(httpWebResponse.CharacterSet).GetString(response.Byte);
            }
            else
            {
                response.String = Encoding.UTF8.GetString(response.Byte);
            }

            #endregion 获取 ResponseByte & ResponseString

            return response;
        }

        /// <summary>
        ///     4.0以下.net版本取数据使用
        /// </summary>
        /// <param name="streamResponse">流</param>
        private MemoryStream Stream2MemoryStream(Stream streamResponse)
        {
            using (var ms = new MemoryStream())
            {
                const int len = 256;
                var buffer = new byte[len];
                var bytesRead = streamResponse.Read(buffer, 0, len);
                while (bytesRead > 0)
                {
                    ms.Write(buffer, 0, bytesRead);
                    bytesRead = streamResponse.Read(buffer, 0, len);
                }
                return ms;
            }
        }

        public static bool SetAllowUnsafeHeaderParsing20(bool useUnsafe)
        {
            //Get the assembly that contains the internal class
            var aNetAssembly = Assembly.GetAssembly(typeof(SettingsSection));
            //Use the assembly in order to get the internal type for the internal class
            var aSettingsType = aNetAssembly?.GetType("System.Net.Configuration.SettingsSectionInternal");
            //Use the internal static property to get an instance of the internal settings class.
            //If the static instance isn't created allready the property will create it for us.
            var anInstance = aSettingsType?.InvokeMember("Section",
                BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null,
                new object[] {});

            if (anInstance != null)
            {
                //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
                var aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing",
                    BindingFlags.NonPublic | BindingFlags.Instance);
                if (aUseUnsafeHeaderParsing != null)
                {
                    aUseUnsafeHeaderParsing.SetValue(anInstance, useUnsafe);
                    return true;
                }
            }
            return false;
        }
    }
}